Ext.setup({
    icon: 'icon.png',
    tabletStartupScreen: 'tablet_startup.png',
    phoneStartupScreen: 'phone_startup.png',
    glossOnIcon: true,
    
onReady: function() {

// VARSVARSVARSVARSVARSVARSVARSVARSVARSVARSVARSVARSVARSVARS
  var resultInsertionPages = [];
  var numberOfPlayers = 0;
  var player1TotalScore = 0;
  var player2TotalScore = 0;
  var player3TotalScore = 0;
  var player4TotalScore = 0;
  var resultsPage = new Ext.form.FormPanel();
 
  var startRoundButton = new Ext.Button({
    ui  : 'confirm',
    text: 'Start round',
    handler: initializeRound
  });
  
  var countResultsButton = new Ext.Button({
  	ui : 'confirm',
  	text : 'End round',
  	handler: submitScores, 
  	hidden: true
  });
  
  var courseNameInputField = new Ext.form.Text({
    xtype: 'textfield',
    name : 'course',
    label: 'Course:',
    useClearIcon: true,
    autoCapitalize : true 
  });
  
  var player1NameInputField = new Ext.form.Text({
    xtype: 'textfield',
    name : 'player1',
    label: 'Player 1:',
    useClearIcon: true,
    autoCapitalize : false, 
    required: true
  });
  
  var player2NameInputField = new Ext.form.Text({
    xtype: 'textfield',
    name : 'player2',
    label: 'Player 2:',
    useClearIcon: true,
    autoCapitalize : false
  });

  var player3NameInputField = new Ext.form.Text({
    xtype: 'textfield',
    name : 'player3',
    label: 'Player 3:',
    useClearIcon: true,
    autoCapitalize : false
  });

  var player4NameInputField = new Ext.form.Text({
    xtype: 'textfield',
    name : 'player4',
    label: 'Player 4:',
    useClearIcon: true,
    autoCapitalize : false
  });

  var frontpageContent = {
    url   : 'postUser.php',
    standardSubmit : false,
    scroll: 'vertical',
    items: [{
      xtype: 'fieldset', 
      title: 'Course details',
      defaults: {
    	  required: true,
    	  labelAlign: 'left'
      },
      items: [courseNameInputField]
    }, {
    	xtype: 'fieldset',
        title: 'Player names',
        items: [player1NameInputField, player2NameInputField, player3NameInputField, player4NameInputField]
      	}
    ],
  	listeners : {
  		submit : function(form, result){},
  		exception : function(form, result){}
    }
  };
  
  var applicationFormPanel = new Ext.form.FormPanel(frontpageContent);
  
  var carousel = new Ext.Carousel({
	  items: [applicationFormPanel]
  });
  
// VARSVARSVARSVARSVARSVARSVARSVARSVARSVARSVARSVARSVARSVARSVARSVARSVARSVARSVARSVARSVARSVARS

// FUNCTIONSFUNCTIONSFUNCTIONSFUNCTIONSFUNCTIONSFUNCTIONSFUNCTIONSFUNCTIONSFUNCTIONSFUNCTIONS
  
  function addPlayerSelects(selects) {
	  for (var i=0; i<18; i++) {
		  var tmp = i+1;
		  resultInsertionPages[i] = new Ext.form.FormPanel({
			  url   : 'postResults.php',
			  standardSubmit : false,
			  items: [{
				  xtype: 'fieldset',
				  id: 'resultSet',
				  title: 'Hole: ' + tmp,
				  instructions: 'Insert player results for hole. Swipe to next hole',
				  items: [{
					  xtype: 'textfield',
					  name: 'holeNumber',
					  value: tmp,
					  hidden: 'true'
	    			}, selects],
	    			listeners : {
	    				submit : function(form, result){},
	    				exception : function(form, result){}
	         		}
			  }]
		  });
	  }
  }  

// FUNCTIONSFUNCTIONSFUNCTIONSFUNCTIONSFUNCTIONSFUNCTIONSFUNCTIONSFUNCTIONSFUNCTIONSFUNCTIONS
  
  if (Ext.is.AndroidOS) {
	  frontpageContent.items.unshift({
		  xtype: 'component',
		  styleHtmlContent: true,
		  html: '<span style="color: red">Forms on Android are currently under development. We are working hard to improve this in upcoming releases.</span>'
      });
  }
  if (Ext.is.Phone) {
	  frontpageContent.fullscreen = true;
  } 
  else {
	  Ext.apply(frontpageContent, {
		  autoRender: true,
		  height: 385,
      });
  }
        
  applicationFormPanel.add(startRoundButton);

  page2 = new Ext.Panel({
    fullscreen: true,
    layout: {type: 'card', align: 'stretch'},
    defaults: {flex: 2},
    items: [applicationFormPanel, carousel],
    dockedItems: [{
    	dock : 'top',
    	xtype: 'toolbar',
    	title: 'Disc Golf Mobile',
    }, {
    	dock: 'bottom',
    	xtype: 'toolbar',
    	items: [{xtype: 'spacer'}, startRoundButton, countResultsButton]
      }]
  });

  function initializeRound() {
	  page2.setActiveItem(carousel);
	  startRoundButton.hide();
	  countResultsButton.show();

  var player1ScoreSelect = {
    items: [{
    	xtype: 'spinnerfield',
    	name: 'player1',
    	value: '0',
    	label: player1NameInputField.getValue() + ':',
    }, {
    	xtype: 'textfield',
    	name: 'player1Name',
    	value: player1NameInputField.getValue(),
    	hidden: 'true'
    }]
  };

  var player2ScoreSelect = {
    items: [{
    	xtype: 'spinnerfield',
    	name: 'player2',
    	value: '0',
    	label: player2NameInputField.getValue() + ':',
    }, {
    	xtype: 'textfield',
    	name: 'player2Name',
    	value: player2NameInputField.getValue(),
    	hidden: 'true'
    }]
  };

  var player3ScoreSelect = {
    items:	[{
    	xtype: 'spinnerfield',
    	name: 'player3',
    	value: '0',
    	label: player3NameInputField.getValue() + ':',
    }, {
    	xtype: 'textfield',
    	name: 'player3Name',
    	value: player3NameInputField.getValue(),
    	hidden: 'true'
    }]
  };

  var player4ScoreSelect = {
    items: [{
    	xtype: 'spinnerfield',
    	name: 'player4',
    	value: '0',
    	label: player4NameInputField.getValue() + ':',
    }, {
    	xtype: 'textfield',
    	name: 'player4Name',
    	value: player4NameInputField.getValue(),
    	hidden: 'true'
    }]
  };

// --------- WRITE Course and names TO DB!! -----------
  applicationFormPanel.submit({waitMsg : {message:'Submitting', cls : 'submitting'}});    
    
  // Disable first page
  courseNameInputField.disable();
  player1NameInputField.disable();
  player2NameInputField.disable();
  player3NameInputField.disable();
  player4NameInputField.disable();
  startRoundButton.hide();
  var selects = [];

  if (player1NameInputField.getValue().length > 0 && player2NameInputField.getValue().length == 0 &&
      player3NameInputField.getValue().length == 0 && player4NameInputField.getValue().length == 0) {
    selects = [player1ScoreSelect];
    addPlayerSelects(selects);
    numberOfPlayers = 1;
  }

  if (player1NameInputField.getValue().length > 0 && player2NameInputField.getValue().length > 0 &&
      player3NameInputField.getValue().length == 0 && player4NameInputField.getValue().length == 0) {
    selects = [player1ScoreSelect, player2ScoreSelect];
    addPlayerSelects(selects);
    numberOfPlayers = 2;
  }

  if (player1NameInputField.getValue().length > 0 && player2NameInputField.getValue().length > 0 &&
      player3NameInputField.getValue().length > 0 && player4NameInputField.getValue().length == 0) {
    selects = [player1ScoreSelect, player2ScoreSelect, player3ScoreSelect];
    addPlayerSelects(selects);
    numberOfPlayers = 3;
  }
  
  if (player1NameInputField.getValue().length > 0 && player2NameInputField.getValue().length > 0 &&
      player3NameInputField.getValue().length > 0 && player4NameInputField.getValue().length > 0) {
    selects = [player1ScoreSelect, player2ScoreSelect, player3ScoreSelect, player4ScoreSelect];
    addPlayerSelects(selects);
    numberOfPlayers = 4;
  }

  for (var i=0; i<18; i++) {
	  carousel.add(resultInsertionPages[i]);
	  carousel.doLayout();
  }
  
} // <---------- InitializeRound

function submitScores() {

  for (var i=0; i<18; i++) {
    player1TotalScore = player1TotalScore + parseInt(resultInsertionPages[i].getValues(true).player1);
    player2TotalScore = player2TotalScore + parseInt(resultInsertionPages[i].getValues(true).player2);
    player3TotalScore = player3TotalScore + parseInt(resultInsertionPages[i].getValues(true).player3);
    player4TotalScore = player4TotalScore + parseInt(resultInsertionPages[i].getValues(true).player4);
  }

  var resultPage1 = {
        url   : 'postTotal.php',
        standardSubmit : false,
        items: [{
          xtype: 'fieldset',
          id: 'resultCount',
          title: 'Results:',
          items: [{
                  xtype: 'textfield',
                  name: 'player1Total',
                  label: player1NameInputField.getValue() + ':',
                  value: player1TotalScore,
                  }, {
                  xtype: 'textfield',
                  name: 'player1Name',
                  value: player1NameInputField.getValue(),
                  hidden: 'true'
                  }],
          listeners : {
                submit : function(form, result){
                    console.log('success', Ext.toArray(arguments));
                },
                exception : function(form, result){
                    console.log('failure', Ext.toArray(arguments));
                }
         }
        }]
  };

  var resultPage2 = {
        url   : 'postTotal.php',
        standardSubmit : false,
        items: [{
          xtype: 'fieldset',
          id: 'resultCount',
          title: 'Results:',
          items: [{
                  xtype: 'textfield',
                  name: 'player1Total',
                  label: player1NameInputField.getValue() + ':',
                  value: player1TotalScore,
               }, {
                  xtype: 'textfield',
                  name: 'player1Name',
                  value: player1NameInputField.getValue(),
                  hidden: 'true'
                },{
                  xtype: 'textfield',
                  name: 'player2Total',
                  label: player2NameInputField.getValue() + ':',
                  value: player2TotalScore,
                 }, {
                  xtype: 'textfield',
                  name: 'player2Name',
                  value: player2NameInputField.getValue(),
                  hidden: 'true'
                  }],
          listeners : {
                submit : function(form, result){
                    console.log('success', Ext.toArray(arguments));
                },
                exception : function(form, result){
                    console.log('failure', Ext.toArray(arguments));
                }
         }
        }]
  };

  var resultPage3 = {
        url   : 'postTotal.php',
        standardSubmit : false,
        items: [{
          xtype: 'fieldset',
          id: 'resultCount',
          title: 'Results:',
          instructions: 'The winner is...',
          items: [{
                  xtype: 'textfield',
                  name: 'player1Total',
                  label: player1NameInputField.getValue() + ':',
                  value: player1TotalScore,
               }, {
                  xtype: 'textfield',
                  name: 'player1Name',
                  value: player1NameInputField.getValue(),
                  hidden: 'true'
                },{
                  xtype: 'textfield',
                  name: 'player2Total',
                  label: player2NameInputField.getValue() + ':',
                  value: player2TotalScore,
                 }, {
                  xtype: 'textfield',
                  name: 'player2Name',
                  value: player2NameInputField.getValue(),
                  hidden: 'true'
                  },
                 {
                  xtype: 'textfield',
                  name: 'player3Total',
                  label: player3NameInputField.getValue() + ':',
                  value: player3TotalScore,
                 }, {
                  xtype: 'textfield',
                  name: 'player3Name',
                  value: player3NameInputField.getValue(),
                  hidden: 'true'
                  }],
          listeners : {
                submit : function(form, result){
                    console.log('success', Ext.toArray(arguments));
                },
                exception : function(form, result){
                    console.log('failure', Ext.toArray(arguments));
                }
         }
        }]
  };

  var resultPage4 = {
        url   : 'postTotal.php',
        standardSubmit : false,
        items: [{
          xtype: 'fieldset',
          id: 'resultCount',
          title: 'Results:',
          instructions: 'The winner is...',
          items: [{
                  xtype: 'textfield',
                  name: 'player1Total',
                  label: player1NameInputField.getValue() + ':',
                  value: player1TotalScore,
               }, {
                  xtype: 'textfield',
                  name: 'player1Name',
                  value: player1NameInputField.getValue(),
                  hidden: 'true'
                },{
                  xtype: 'textfield',
                  name: 'player2Total',
                  label: player2NameInputField.getValue() + ':',
                  value: player2TotalScore,
                 }, {
                  xtype: 'textfield',
                  name: 'player2Name',
                  value: player2NameInputField.getValue(),
                  hidden: 'true'
                  },
                 {
                  xtype: 'textfield',
                  name: 'player3Total',
                  label: player3NameInputField.getValue() + ':',
                  value: player3TotalScore,
                 }, {
                  xtype: 'textfield',
                  name: 'player3Name',
                  value: player3NameInputField.getValue(),
                  hidden: 'true'
                  }, {
                  xtype: 'textfield',
                  name: 'player4Total',
                  label: player4NameInputField.getValue() + ':',
                  value: player4TotalScore,
                 }, {
                  xtype: 'textfield',
                  name: 'player4Name',
                  value: player4NameInputField.getValue(),
                  hidden: 'true'
                  }],
          listeners : {
                submit : function(form, result){
                    console.log('success', Ext.toArray(arguments));
                },
                exception : function(form, result){
                    console.log('failure', Ext.toArray(arguments));
                }
         }
        }]
  };

// TODO IF numberofplayers == 1 -> Hide rest! :)
  
  if (numberOfPlayers == 1) {
    resultsPage.add(resultPage1);
  }
  if (numberOfPlayers == 2) {
    resultsPage.add(resultPage2);
  }
  if (numberOfPlayers == 3) {
    resultsPage.add(resultPage3);
  }
  if (numberOfPlayers == 4) {
    resultsPage.add(resultPage4);
  }

  resultsPage.doLayout();
  carousel.add(resultsPage);
  carousel.doLayout();
  carousel.setActiveItem(18);
  
// ------- ADD player results TO DB ------------
	for (var i=0; i<18; i++) {
      resultInsertionPages[i].submit({waitMsg : {message:'Submitting', cls : 'submitting'}});
  }

// ------- ADD player total scores TO DB ------------
resultsPage.submit({waitMsg : {message:'Submitting', cls : 'submitting'}});
countResultsButton.disable();

} // <--------- SUBMIT SCORES LOPPUU

} // <--------- OnREady LOPPUU

}); // <------ Ext.Setup LOPPUU